interface ExtendedWindow extends Window {
  lib: any; 
  dpr: number;
  rem: number;
}

(function (win: ExtendedWindow, lib: any) {
  const doc: Document = win.document;
  const docEl: HTMLElement = doc.documentElement;
  let metaEl: HTMLMetaElement | null = doc.querySelector('meta[name="viewport"]');
  const flexibleEl: HTMLMetaElement | null = doc.querySelector('meta[name="flexible"]');
  let dpr: number = 0;
  let scale: number = 0;
  let tid: number;
  const flexible = lib.flexible || (lib.flexible = {});

  if (metaEl) {
    console.warn('将根据已有的meta标签来设置缩放比例');
    const match = metaEl.getAttribute('content')?.match(/initial-scale=([\d.]+)/);
    if (match) {
      scale = parseFloat(match[1]);
      dpr = parseInt((1 / scale).toString(), 10);
    }
  } else if (flexibleEl) {
    const content = flexibleEl.getAttribute('content');
    if (content) {
      const initialDpr = content.match(/initial-dpr=([\d.]+)/);
      const maximumDpr = content.match(/maximum-dpr=([\d.]+)/);
      if (initialDpr) {
        dpr = parseFloat(initialDpr[1]);
        scale = parseFloat((1 / dpr).toFixed(2));
      }
      if (maximumDpr) {
        dpr = parseFloat(maximumDpr[1]);
        scale = parseFloat((1 / dpr).toFixed(2));
      }
    }
  }
  
  
  if (!dpr && !scale) {
    const isAndroid: boolean = /android/i.test(win.navigator.userAgent);
    const isIPhone: boolean = /iphone/i.test(win.navigator.userAgent);
    const devicePixelRatio = win.devicePixelRatio;
    if (isIPhone) {
      if (devicePixelRatio >= 3 && (!dpr || dpr >= 3)) {
        dpr = 3;
      } else if (devicePixelRatio >= 2 && (!dpr || dpr >= 2)) {
        dpr = 2;
      } else {
        dpr = 1;
      }
    } else {
      dpr = 1;
    }
    scale = 1 / dpr;
  }

  docEl.setAttribute('data-dpr', dpr.toString());

  if (!metaEl) {
    metaEl = doc.createElement('meta');
    metaEl.setAttribute('name', 'viewport');
    metaEl.setAttribute(
      'content',
      `initial-scale=${scale}, maximum-scale=${scale}, minimum-scale=${scale}, user-scalable=no`
    );
    if (docEl.firstElementChild) {
      docEl.firstElementChild.appendChild(metaEl);
    } else {
      const wrap = doc.createElement('div');
      wrap.appendChild(metaEl);
      doc.write(wrap.innerHTML);
    }
  }

  function refreshRem(): void {
    let width = docEl.getBoundingClientRect().width;
    if (width / dpr > 500) {
      width = 500 * dpr;
    }
    // const rem = width >= 450 ? 100 : width / 3.75;
    const rem =  width / 3.75;
    docEl.style.fontSize = `${rem}px`;
    console.log(rem);
    
    flexible.rem = win.rem = rem;
  }

  win.addEventListener('resize',() => {
      clearTimeout(tid);
      tid = window.setTimeout(refreshRem, 300);
    },
    false
  );

  win.addEventListener('pageshow',(e: PageTransitionEvent) => {
      if (e.persisted) {
        clearTimeout(tid);
        tid = window.setTimeout(refreshRem, 300);
      }
    },
    false
  );

  if (doc.readyState === 'complete') {
    doc.body.style.fontSize = `${12 * dpr}px`;
  } else {
    doc.addEventListener('DOMContentLoaded',() => {
        doc.body.style.fontSize = `${12 * dpr}px`;
      },
      false
    );
  }

  refreshRem();

  flexible.dpr = win.dpr = dpr;
  flexible.refreshRem = refreshRem;
  flexible.rem2px = function (d: number | string): string | number {
    const val = parseFloat(d as string) * this.rem;
    if (typeof d === 'string' && d.match(/rem$/)) {
      return `${val}px`;
    }
    return val;
  };
  flexible.px2rem = function (d: number | string): string | number {
    const val = parseFloat(d as string) / this.rem;
    if (typeof d === 'string' && d.match(/px$/)) {
      return `${val}rem`;
    }
    return val;
  };
})(window as unknown as ExtendedWindow, (window as unknown as ExtendedWindow)['lib'] || ((window as unknown as ExtendedWindow)['lib'] = {}));
